#include "gitlnonblockevtdispatcher.h"

GitlNonBlockEvtDispatcher::GitlNonBlockEvtDispatcher(QList<GitlModual *> *pcModuals) :
    m_pcModuals(pcModuals)
{
}

GitlNonBlockEvtDispatcher::~GitlNonBlockEvtDispatcher()
{
    QMutexLocker cHandlerLocker(&m_cEvtHandlerQueLocker);

    while( !m_cNonBlockEvtHandlerThreads.empty() )
    {
        GitlNonBlockEvtHandlerThread* pcHandlerThread = m_cNonBlockEvtHandlerThreads.back();
        pcHandlerThread->terminate();
        pcHandlerThread->wait();
        delete pcHandlerThread;
        m_cNonBlockEvtHandlerThreads.pop_back();
    }
}


/*! non-blocking notification
  */
void GitlNonBlockEvtDispatcher::postEvent(GitlEvent* pcEvt)
{
    QMutexLocker cHandlerLocker(&m_cEvtHandlerQueLocker);

    GitlNonBlockEvtHandlerThread *pcHandlerThread = NULL;
    for( int i = 0; i < m_cNonBlockEvtHandlerThreads.size(); i++ )
    {
        if( m_cNonBlockEvtHandlerThreads[i]->isRunning() == false )
        {
            pcHandlerThread = m_cNonBlockEvtHandlerThreads[i];
            break;
        }
    }
    if( pcHandlerThread == NULL )
    {
        GitlIOMsg::getInstance()->msgOut("new thread");
        pcHandlerThread = new GitlNonBlockEvtHandlerThread(m_pcModuals);
        m_cNonBlockEvtHandlerThreads.push_back(pcHandlerThread);
    }

    pcHandlerThread->setEvt(*pcEvt);
    pcHandlerThread->start();

}


